package com.ebt.m.wiki.util;

import android.content.Context;
import android.util.Log;

import com.ebt.m.R;
import com.ebt.m.data.entity.NewProductInfo;
import com.ebt.m.data.entity.ProductInfo;
import com.ebt.m.commons.utils.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WikiUtils {

    public static final int SEND_REQUEST_OK = 1;
    public static final int SEND_REQUEST_FAILED = 0;
    public static final int SEND_RESULT_SUCCESS = 1;
    public static final String PRODUCT_URL_PREFIX = "http://ebtres.oss-cn-hangzhou.aliyuncs.com/Doc/";
    public static final String PRODUCT_RULE_URL_SUFFIX = "/policy.html";
    public static final String PRODUCT_CLAUSE_URL_SUFFIX = "/autoexplain.xml";
    /*产品推荐排序url-使用时后面跟品牌id*/
    public static final String PRODUCT_COMMOND_ORDER_URL_PREFIX = "https://datapi.e-bao.cn/dat/brand/productorder/";
    //TODO
    /*public static void shareProductNoCategory(final Handler handler) {
        JSONObject paramsObj = new JSONObject();
		JSONArray parameterArray = new JSONArray();
		try {
			paramsObj.put("ServiceName", "DeliverProduct");
			JSONObject agentInfo = new JSONObject();
			agentInfo.put("name", "AgentInfo");
			agentInfo.put("value", WikiDetailActivity.pAgentInfo);
			parameterArray.put(0, agentInfo);

			JSONObject pushInfo = new JSONObject();
			pushInfo.put("name", "PushInfo");
			pushInfo.put("value", WikiDetailActivity.pPushInfo);
			parameterArray.put(1, pushInfo);

			JSONObject productInfo = new JSONObject();
			productInfo.put("name", "Products");
			productInfo.put("value", WikiDetailActivity.pProductInfo);
			parameterArray.put(2, productInfo);

			paramsObj.put("Parameters", parameterArray);
			
			sendProductRequest(handler, paramsObj.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public static void sendProductRequest(final Handler handler, final String parameters) {

		new Thread() {
			@Override
			public void run() {
				Message msg = handler.obtainMessage();
				try {
					String json = sendRequest(parameters);
					msg.arg1 = SEND_REQUEST_OK;
					msg.obj = json;
				} catch (EBTSoapHeaderException e) {
					msg.arg1 = SEND_REQUEST_FAILED;
				} catch (Exception e) {
					msg.arg1 = SEND_REQUEST_FAILED;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}

	private static String sendRequest(String params) throws HttpException,
			EBTSoapHeaderException, IOException, Exception {
		String wsdl = DownloaderConstants.URL_YIBAONET_WSDL;
		String soapAction = DownloaderConstants.URL_YIBAONET_ACTION;
		String method = DownloaderConstants.URL_YIBAONET_METHOD;
		String xmlns = DownloaderConstants.URL_YIBAONET_XMLNS;
		Map pamps = new HashMap();
		pamps.put("strJson", params);
		
		EventLogUtils.saveUserLog("SHARE_PRODUCT", getProductName(), "");
		
		return WebServiceRequestHelper.sendRequestByNoAccount(pamps, 
				 wsdl, soapAction, method, xmlns);
	}
	
	public static String getAgentName() {
		try {
			JSONObject newProductInfo = new JSONObject(
					WikiDetailActivity.pAgentInfo);
			return newProductInfo.getString("AgentName");
		} catch (JSONException e) {
			return null;
		}
	}
	
	public static String getProductName() {
		try {
			JSONObject newProductInfo = new JSONObject(
					WikiDetailActivity.pProductInfo);
			return newProductInfo.getString("ProductName");
		} catch (JSONException e) {
			return null;
		}
	}*/

    public static String loadJSONFromAsset(Context c) {
        String json = null;
        try {

            InputStream is = c.getAssets().open("test.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            return null;
        }
        return json;
    }

    /**
     * 获取性别字符串
     *
     * @param mContext
     * @param age
     * @return
     */
    public static String getSexStr(Context mContext, int age) {
        String[] strs = mContext.getResources().getStringArray(R.array.common_sex);
        return strs[age];
    }

    /**
     * 获取性别字符串
     *
     * @param mContext
     * @param cate
     * @return
     */
    public static String getCateStr(Context mContext, int cate) {
        String[] strs = mContext.getResources().getStringArray(R.array.common_professional);
        return strs[cate];
    }

    public static void downloadFile(String url, String destPath) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(destPath);
                    if (file.exists()) {
                        file.delete();
                    }
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                    }
                    fos.flush();
                    Logger.d("文件下载成功");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("h_bl", "onFailure");
            }
        });
    }

    /**
     * @param newProductInfo
     * @return
     */
    public static ProductInfo getProductInfoFromNewProductInfo(NewProductInfo newProductInfo){
        ProductInfo productInfo = new ProductInfo();
        productInfo.Id = newProductInfo.getProductId();
        productInfo.ProductId = newProductInfo.getProductId();
        productInfo.ContractProperty = newProductInfo.isMain()?1:0;
        productInfo.Name = newProductInfo.getName();
        productInfo.ShortName = newProductInfo.getShortName();
        productInfo.Description = newProductInfo.getDescription();
        productInfo.Thumbnail = newProductInfo.getThumbnail();
        productInfo.companyName = newProductInfo.getCompanyName();
        productInfo.companyShortName  = newProductInfo.getCompanyShortName();
        return productInfo;
    }
}
